package com.ruoyi.common.security.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.EncryptAesUtil;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import sun.net.www.http.HttpClient;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.PathMatcher;
import java.util.Enumeration;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 * app端自定义拦截器，解析url请求地址，参数，加密返回结果
 * @author ruoyi
 */
public class HeaderAppInterceptor implements AsyncHandlerInterceptor
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        //if(interfaceForward(request,response,handler)){
        //    return true;
        //}
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }

        SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
        SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
        String token = SecurityUtils.getToken();
        if (StringUtils.isNotEmpty(token))
        {
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if (StringUtils.isNotNull(loginUser))
            {
                AuthUtil.verifyLoginUserExpire(loginUser);
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
                SecurityContextHolder.setFullName(loginUser.getSysUser().getNickName());
            }
        }
        return true;
    }

    ///**
    // * 接口转发
    // * @param request
    // * @param response
    // * @param handler
    // * @return
    // */
    //private static boolean interfaceForward(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
    //    StringBuffer oldUrl = request.getRequestURL();
    //    //if(oldUrl.toString().matches("(.*)/error(.*)")){
    //    if(oldUrl.toString().matches("(.*)/system-app(.*)")){
    //        String path = "";
    //        //String param="";
    //        //String method="";
    //        String sign = request.getHeader("SIGN");
    //        String[] str={DateUtils.dateTimeNowLong(),DateUtils.dateTimeNowLong()+"1",DateUtils.dateTimeNowLong()+"2"};
    //        boolean result = false;
    //        JSONObject jsonObj=new JSONObject();
    //        //json解析
    //        for (String time:str){
    //            String json = EncryptAesUtil.decrypt(request.getSession().getId(),time,sign);
    //            try {
    //                Object obj= JSONObject.parse(json);
    //                jsonObj= (JSONObject) obj;
    //                result=true;
    //                break;
    //            } catch (Exception e) {
    //                continue;
    //            }
    //        }
    //        if(!result){
    //            return result;
    //        }
    //        if(jsonObj.containsKey("path")){
    //            path=jsonObj.getString("path");
    //        }
    //        //if(jsonObj.containsKey("param")){
    //        //    param=jsonObj.getString("param");
    //        //
    //        //}
    //        //if(jsonObj.containsKey("method")){
    //        //    method=jsonObj.getString("method");
    //        //}
    //        //request = new ParameterRequestWrapper(request, StringUtils.getStringToMap(param));
    //        ////request.getMethod()
    //        //ServletRequest requestWrapper = new ParameterRequestWrapper(request);
    //        RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
    //        requestDispatcher.forward(request,response);
    //    }
    //    return true;
    //}


    //public static void main(String[] args) {
    //    String Str = new String("127.0.0.1:8081/system-app/dict");
    //    System.out.println("127.0.0.1:8081/system-app/dict".matches("(.*)/system-app/(.*)"));
    //}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        SecurityContextHolder.remove();
    }
}
